package integraltask

import (
	"context"
	"fmt"
	"strings"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/types/setting"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetIntegralTaskByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetIntegralTaskByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetIntegralTaskByIdLogic {
	return &GetIntegralTaskByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetIntegralTaskByIdLogic) GetIntegralTaskById(in *setting.IntegralTaskDetailReq) (*setting.IntegralTaskInfo, error) {
	logx.Infof("GetIntegralTaskById : %+v ", in)
	if (in.Filter == nil || len(*in.Filter) == 0) && (in.Id == nil || *in.Id == 0) {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	preloadMap, eagerLoadMap := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)

	logrus.Info(fmt.Sprintf("GetIntegralTaskById preloadMap: %+v", preloadMap))

	logrus.Info(fmt.Sprintf("GetIntegralTaskById eagerLoadMap: %+v", eagerLoadMap))

	integralTaskEntityName := model.RpcEntityNames.IntegralTask
	if _, ok := model.RpcEntityPreloadMap[integralTaskEntityName]; !ok {
		return &setting.IntegralTaskInfo{}, nil
	}

	integralTaskRepositoryName := model.RepositoryNames.IntegralTask
	columnMap, ok := model.RepositoryPreloadMap[integralTaskRepositoryName]
	if !ok {
		return &setting.IntegralTaskInfo{}, nil
	}

	var task *model.SysUserIntegralTask
	if in.Id != nil && *in.Id > 0 {
		data, err := l.svcCtx.IntegralTask.FindOne(l.ctx, *in.Id)
		if err != nil {
			return nil, err
		}

		task = data
	} else {
		var selectCols []string
		if preloadFields, ok := preloadMap[integralTaskEntityName]; ok {
			selectCols = modelx.ParseSelectColumns(preloadFields, columnMap)
		}

		filterMap := modelx.ParseFilter(in.Filter, columnMap)
		logrus.Info(fmt.Sprintf("GetPostById filterMap: %+v", filterMap))
		if filterMap == nil {
			return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
		}

		orderBy := modelx.ParseSorter(in.Sorter, columnMap)
		logrus.Info(fmt.Sprintf("GetPostById orderBy: %s", orderBy))
		if len(orderBy) == 0 {
			orderBy = model.SysUserIntegralTaskColumns.ID + " DESC"
		}

		res, _, err := l.svcCtx.IntegralTask.GetList(l.ctx, model.M{
			"pageSize": uint64(1),
			"orderBy":  orderBy,
			"select":   strings.Join(selectCols, ","),
		}, -1, filterMap)
		if err != nil {
			return nil, err
		}

		if len(res) == 0 {
			return &setting.IntegralTaskInfo{}, nil
		}

		task = res[0]
	}
	if task == nil {
		return &setting.IntegralTaskInfo{}, nil
	}

	if task.Status == uint8(globalkey.StatusDeleted) {
		return &setting.IntegralTaskInfo{}, nil
	}

	return &setting.IntegralTaskInfo{
		Id:            &task.ID,
		RuleName:      &task.RuleName,
		RuleSlug:      &task.RuleSlug,
		RuleType:      pointy.GetPointer(uint32(task.RuleType)),
		PicId:         &task.PicID,
		PicUrl:        &task.PicURL,
		Frequency:     pointy.GetPointer(uint32(task.Frequency)),
		Points:        &task.Points,
		EffectiveTime: pointy.GetPointer(modelx.FormatTime(task.EffectiveTime, "")),
		Ip:            &task.IP,
		Description:   pointy.GetPointer(modelx.FormatNullDotString(task.Description)),
		Sort:          pointy.GetPointer(uint32(task.Sort)),
		Status:        pointy.GetPointer(uint32(task.Status)),
		CreatedAt:     pointy.GetPointer(modelx.FormatTime(task.CreatedAt, "")),
		UpdatedAt:     pointy.GetPointer(modelx.FormatTime(task.UpdatedAt, "")),
		DeletedAt:     pointy.GetPointer(modelx.FormatNullDotTime(task.DeletedAt, "")),
	}, nil
}
